/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dao;

import conexion.ConexionFactory;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import javax.swing.JOptionPane;
import modelos.Orden;
import org.jdesktop.observablecollections.ObservableCollections;
import presentacion.Ordenes;
import recursos.XML;

/**
 *
 * @author luramirez
 */
public class OrderDao implements IOrdersDao {

    private DetalleOrdenDao ordenDetail;

    @Override
    public List<Orden> getOrdenes() throws Exception {

        Connection sqlc = null;
        List<Orden> result = null;
        ResultSet rs = null;
        PreparedStatement pstmt = null;

        try {

            sqlc = ConexionFactory.getInstance().getConexion();
            pstmt = sqlc.prepareStatement("SELECT * FROM vw_Ordenes");
            rs = pstmt.executeQuery();
            // inicializar la lista como vacia
            result = new ArrayList<>();

            // mapea (pasa/copia) los registros resultantes SQL a la lista
            while (rs.next()) {
                Orden objUsuario = Helper.getOrden(rs, this);
                objUsuario.setDetalleOrden(ObservableCollections.observableList(new LinkedList(getDetalleOrdenDao().getDetalleOrden(objUsuario.getIdOrden()))));
                result.add(objUsuario);
            }

        } catch (NullPointerException ex) {
            throw new Exception("La Conexion es Nula o Hay Problemas en la Red.");
        } catch (Exception ex) {
            throw new Exception(ex.getCause().getMessage());

        }
        return result;
    }

    public DetalleOrdenDao getDetalleOrdenDao() {
        if (ordenDetail == null) {
            ordenDetail = new DetalleOrdenDao();
        }
        return ordenDetail;
    }

    @Override
    public Orden getOrdenById(Long id) throws Exception {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public void procesarOrden(Orden orden, Integer opcion) throws Exception {
        Connection sqlc = null;
        CallableStatement cstmt = null;
        try {
            sqlc = ConexionFactory.getInstance().getConexion();
            String sqlStmt = "{ call sp_xml_orders " + fillParams(3)
                    + "}";
            cstmt = sqlc.prepareCall(sqlStmt);
            int i = 1;
            cstmt.setInt(i++, opcion);
            cstmt.setInt(i++, orden.getId());
            cstmt.setString(i++, new XML(orden).getXMLString());
            cstmt.execute();
             JOptionPane.showMessageDialog(null,"Elemento Guardado Correctamente");
        } catch (Exception ex) {
            System.out.println("error al procesar Orden "+ ex.getMessage());
            JOptionPane.showMessageDialog(null,"Elemento debe de tener minimo un Detalle");
        }
    }

    private String fillParams(int count) {
        String result = "(";
        for (int i = 1; i <= count; i++) {
            if (i < count) {
                result += "?,";
            } else {
                result += "?)";
            }
        }
        return result;
    }
}
